<template>
  <div class="todo-container">
    <div class="todo-wrap">
      <Header @addTodo="addTodo" />
      <List :todoList="todoList" @updateTodo="updateTodo" @delTodo="delTodo" />
      <Footer
        :totalNum="todoList.length"
        :isDoneNum="isDoneNum"
        @updateAllTodo="updateAllTodo"
        @delAllTodo="delAllTodo"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
// 引入组件会自动注册
import Header from "./views/header/index.vue";
import List from "./views/list/index.vue";
import Footer from "./views/footer/index.vue";

// 引入类型建议加上type
import type { TodoList, TodoItem } from "./types";
// 待办事项
const todoList = ref<TodoList>([{ id: 1, title: "睡觉", isDone: false }]);

// 添加todo
const addTodo = (title: string) => {
  todoList.value.push({
    id: Date.now(),
    title,
    isDone: false,
  });
};

// 数据源在哪，更新数据的方法就在哪。
// 单选
const updateTodo = (id: number) => {
  // find方法找到返回todo，找不到返回undefined
  // 联合类型想要当做其中一个类型去使用，使用类型断言
  const todo = todoList.value.find((todo) => todo.id === id) as TodoItem;
  todo.isDone = !todo.isDone;
};

// 单个删除
const delTodo = (id: number) => {
  todoList.value = todoList.value.filter((todo) => todo.id !== id);
};
// 已完成数量
const isDoneNum = computed(() => {
  return todoList.value.reduce((p, c) => {
    return p + (c.isDone ? 1 : 0);
  }, 0);
});
// 全选
const updateAllTodo = (isDone: boolean) => {
  todoList.value.forEach((todo) => {
    todo.isDone = isDone;
  });
};
// 批量删除
const delAllTodo = () => {
  todoList.value = todoList.value.filter((todo) => !todo.isDone);
};
</script>

<style scoped>
/*app*/
.todo-container {
  width: 600px;
  margin: 0 auto;
}
.todo-container .todo-wrap {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}
</style>
